'use strict';

const Controller = require('egg').Controller;

class FavapiController extends Controller {

  // 是否收藏了该api
  async isFavApi () {
    const { ctx } = this
    const { username, apiId } = ctx.query
    const result = await ctx.service.fav.findOneFavApi(username, apiId)
    if (result.length) {
      ctx.body= {
        code: 1,
        isfav: true,
        result,
        msg: '已收藏'
      }
    } else {
      ctx.body = {
        code: 2,
        isfav: false,
        msg: '没有收藏'
      }
    }
  }
  // 收藏api
  async favapi() {
    const { ctx } = this
    const { apiId, username, projectId } = ctx.request.body
    const result = await ctx.service.fav.favPai(username, apiId, projectId)
    if (result.affectedRows === 1) {
      // 成功返回
      ctx.body = {
        code: 1,
        msg: '收藏成功'
      }
      return
    }
    // 失败返回
    ctx.body = {
      code: 0,
      msg: '收藏失败'
    }
  }

  // 取消收藏
  async deleteFav () {
    const { ctx } = this
    const { id } = ctx.params
    const result = await ctx.service.fav.deleteFav(id)
    if (result.affectedRows === 1) {
      ctx.body = {
        code: 1,
        msg: '取消收藏成功'
      }
    } else {
      ctx.body = {
        code: 0,
        msg: '取消收藏失败'
      }
    }
  }

  // 我的收藏
  async myfav () {
    const { ctx } = this
    const { username } = ctx.params
    const result = await ctx.service.fav.findApiByUsername(username)
    console.log(result)
    ctx.body = {
      code: 1,
      result
    }
  }

}

module.exports = FavapiController;
